package com.clb.netlibrary.net

import com.clb.netlibrary.BuildConfig
import com.orhanobut.logger.Logger
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit


/***********************************
 * 创建者: clb
 * 创建日期: 2018.10.10.0010
 * 功能 Retrofit类
 ***********************************
 */
object ApiService {

    private var mRetrofit: Retrofit? = null
    private const val BASE_URL = "https://www.baidu.com/"

    /**
     * 获取retrofit
     */
    fun getRetrofit(): ApiInterface {

        return if (mRetrofit == null) {
            val createRetrofit = createRetrofit()
            createRetrofit.create(ApiInterface::class.java)
        } else {
            mRetrofit?.create(ApiInterface::class.java)!!
        }
    }

    private fun createRetrofit(): Retrofit {
        //自定义OkHttpClient
        val okHttpClient = OkHttpClient.Builder()
        //添加拦截器
        okHttpClient
            .addInterceptor(interceptor)
            //设置连接失败重连
            .retryOnConnectionFailure(true)
            //设置连接超时时间
            .connectTimeout(15, TimeUnit.SECONDS)
        return Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addCallAdapterFactory(LiveDataCallAdapterFactory())
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient.build())
            .build()
    }

    /**
     * 请求访问quest    打印日志
     * response拦截器
     */
    private val interceptor = Interceptor { chain: Interceptor.Chain ->
        val request = chain.request().newBuilder().build()//添加请求头
        val response = chain.proceed(request)
        val mediaType = response.body()?.contentType()
        val content = response.body()?.string()
        if (BuildConfig.DEBUG) {
//            Logger.e("ApiRetrofit | $request===========${request.headers()}")
            Logger.e("ApiRetrofit | $request")
            Logger.e("返回的数据:$content" ?: "")
        }
        response.newBuilder().body(ResponseBody.create(mediaType, content ?: "")).build()
    }
}